import React, { useState, useEffect } from "react";
// import { Standard } from '@/api/entities';
import { StandardAPI } from "@/api/Standard";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2, BookCheck } from "lucide-react";

export default function StandardImportModal({
  isOpen,
  onClose,
  onImport,
  existingBasis = [],
}) {
  const [standards, setStandards] = useState([]);
  const [selectedStandards, setSelectedStandards] = useState(new Set());
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");

  useEffect(() => {
    if (isOpen) {
      const fetchStandards = async () => {
        setIsLoading(true);
        try {
          const res = await StandardAPI.getList({ sort: "-created_date" });
          setStandards(res.data || []);
        } catch (error) {
          console.error("获取标准规范失败:", error);
          setStandards([]);
        }
        setIsLoading(false);
      };
      fetchStandards();
    }
  }, [isOpen]);

  const handleSelect = (standardId) => {
    setSelectedStandards((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(standardId)) {
        newSet.delete(standardId);
      } else {
        newSet.add(standardId);
      }
      return newSet;
    });
  };

  const handleImport = () => {
    // const selectedIds = Array.from(selectedStandards);
    // onImport(selectedIds);
    // setSelectedStandards(new Set());
    // onClose();
    const selectedItems = standards.filter((std) =>
      selectedStandards.has(std.id)
    );
    onImport(selectedItems); // 传递完整对象数组
    setSelectedStandards(new Set());
    onClose();
  };

  const filteredStandards = standards.filter(
    (std) =>
      std.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      std.code?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const isAlreadyImported = (standardId) => {
    return existingBasis.includes(standardId);
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent
        className="max-w-2xl max-h-[80vh]"
        aria-describedby="standard-import-description"
      >
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <BookCheck className="w-5 h-5 text-blue-600" />
            从知识库导入编制依据
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <Input
            placeholder="搜索标准名称或编号..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />

          <ScrollArea className="h-80 border rounded-md p-4">
            {isLoading ? (
              <div className="flex items-center justify-center h-full">
                <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
              </div>
            ) : (
              <div className="space-y-2">
                {filteredStandards.length === 0 ? (
                  <div className="text-center py-8 text-gray-500">
                    <BookCheck className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                    <p>暂无匹配的标准规范</p>
                  </div>
                ) : (
                  filteredStandards.map((std) => {
                    const isDisabled = isAlreadyImported(std.id);
                    return (
                      <div
                        key={std.id}
                        className={`flex items-center space-x-3 p-3 rounded-lg border hover:bg-gray-50 ${
                          isDisabled ? "bg-gray-100 opacity-60" : ""
                        }`}
                      >
                        <Checkbox
                          id={std.id}
                          checked={selectedStandards.has(std.id) || isDisabled}
                          onCheckedChange={() =>
                            !isDisabled && handleSelect(std.id)
                          }
                          disabled={isDisabled}
                        />
                        <label
                          htmlFor={std.id}
                          className={`flex-1 text-sm ${
                            isDisabled ? "cursor-not-allowed" : "cursor-pointer"
                          }`}
                        >
                          <div className="font-medium text-gray-800">
                            {std.code}
                          </div>
                          <div className="text-gray-600">{std.name}</div>
                          <div className="text-xs text-gray-400 mt-1">
                            {std.publicationYear &&
                              `发布年份: ${std.publicationYear}`}
                            {std.issuingAuthority &&
                              ` | ${std.issuingAuthority}`}
                          </div>
                          {isDisabled && (
                            <div className="text-xs text-blue-600 mt-1">
                              已导入
                            </div>
                          )}
                        </label>
                      </div>
                    );
                  })
                )}
              </div>
            )}
          </ScrollArea>

          {selectedStandards.size > 0 && (
            <div className="text-sm text-gray-600 bg-blue-50 p-3 rounded-lg">
              已选择 {selectedStandards.size} 个标准规范
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            取消
          </Button>
          <Button
            onClick={handleImport}
            disabled={selectedStandards.size === 0}
            className="bg-blue-600 hover:bg-blue-700"
          >
            导入选中项 ({selectedStandards.size})
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
